import { reduce_time_action, set_game_state_action, set_playEnd_action } from "./actionCreator"
import { useEffect, useState, useRef } from "react"
import style from "./timer.module.css"

const Timer = ({ gameStart, dispatch, time, found }) => {
    let [timer, setTimer] = useState("")
    let [foundClass, setFoundClass] = useState(false)
    let [timeClass, setTimeClass] = useState(false)

    let t = useRef()
    t.current = time
    let tId = useRef()
    tId.current = timer

    useEffect(() => {
        if (gameStart) {
            setFoundClass(true)
            setTimeClass(true)
        }
    }, [found])

    useEffect(() => {
        if (gameStart === true) {
            setTimer(setInterval(() => {
                if (t.current === 0) {
                    clearInterval(tId.current)
                    setTimer("")
                    let action = set_game_state_action(false)
                    dispatch(action)
                    let action2 = set_playEnd_action(true)
                    dispatch(action2)
                } else {
                    let action = reduce_time_action()
                    dispatch(action)
                }
            }, 1000))
        }
    }, [gameStart])

    const formatTime = (t) => {
        return t / 1000
    }

    return (
        <>
            <div className={style.container}>
                <span className={[style.time, timeClass ? style.add_time : ""].join(" ")}
                    onAnimationEnd={() => setTimeClass(false)}>
                    {formatTime(time)}
                </span>
                <span className={style.found}>
                    found pair:
                    <span className={
                        [style.found_num, foundClass ? style.active : ""].join(" ")}
                        onAnimationEnd={() => setFoundClass(false)}>
                        {found}
                    </span>
                </span>
            </div>

        </>
    )
}

export default Timer